<!--  -->
<template>
  <div class="vehicle-container flex-column h-100P">
    <query-container @search="handleSearch" @reset="handleReset">
      <!-- 查询条件 -->
      <div class="justify-between">
        <el-form
          ref="queryForm"
          inline
          :model="queryInfo"
          label-position="left"
          :label-width="handleScreenWidthToVw(70)+'px'"
        >
          <el-form-item label="选择产品" prop="productId">
            <SelectProduct
              :value="{id:queryInfo.productId}"
              @change="({id})=>queryInfo.productId=id"
            />
          </el-form-item>
          <el-form-item label="启用状态" prop="enableStateEnum">
            <SelectDeviceState v-model="queryInfo.enableStateEnum" />
          </el-form-item>
          <el-form-item label="在线状态" prop="online">
            <SelectOnlineState v-model="queryInfo.online" />
          </el-form-item>
          <el-form-item label="" prop="keyword">
            <el-input
              v-model="queryInfo.keyword"
              placeholder="请输入设备名或备注名称"
              clearable
              style="width: 350px;"
            >
              <i slot="suffix" class="el-input__icon el-icon-search" />
            </el-input>
          </el-form-item>
        </el-form>
      </div>
    </query-container>
    <div class="flex-sub content">
      <div class="flex-column h-100P">
        <!-- 添加按钮 -->
        <div class="flex justify-between">
          <div class="flex">
            <custom-button title="新建接入" @click="handleCreateGroup" />
            <custom-button title="批量导入" @click="isCreateVisible=true" class="mg-left-20" />
          </div>
        </div>
        <div class="flex-sub table-container">
          <el-table
            v-loading="loading"
            :data="tableData"
            height="98%"
            header-cell-class-name="table-header-cell"
            header-row-class-name="table-header-row"
          >
            <el-table-column prop="name" label="设备名/备注名称">
              <template v-slot="{row:{name,remarkName}}">
                <div class="cell-style">
                  <div style="color: #1E1E1E;">{{ remarkName }}</div>
                  <div>{{ name }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="personName" label="所属产品">
              <template v-slot="{row:{productVo}}">
                <div class="cell-style">
                  {{ productVo && productVo.name }}
                </div>
              </template>
            </el-table-column>
            <!--            <el-table-column prop="type" label="入网类型">-->
            <!--              <template v-slot="{row:{productVo}}">-->
            <!--                <div class="cell-style">-->
            <!--                  {{ productVo && productVo.netTypeName }}-->
            <!--                </div>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column prop="type" label="网关编号">
              <template v-slot="{row:{gatewayVo}}">
                <div class="cell-style">
                  {{ gatewayVo && gatewayVo.gatewayNo }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="启用状态">
              <template v-slot="{row:{enableStateEnumName,enableStateEnum}}">
                <span :class="enableStateEnum">{{ enableStateEnumName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="online" label="在线状态">
              <template v-slot="{row}">
                <div :style="{color:( row.online?'#67c23a':'#D12D1F')}">
                  {{ row.online ? '在线' : '离线' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="activeTime" label="最近上线时间" sortable>
              <template v-slot="{row}">
                {{ row.activeTime | dateTimeFormatter }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" sortable>
              <template slot-scope="scope">
                <span>{{ scope.row.createTime | dateTimeFormatter }}</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150px" align="center">
              <template slot-scope="scope">
                <div class="justify-center">
                  <div class="btn-edit" @click="handleEdit(scope.row)">查看</div>
                  <!--            <div class="pd-lr-10 fz-14" style="color: #333;">|</div>-->
                  <!--            <div class="btn-edit" @click="handleOpenPlayer(scope.row)">打开视频流</div>-->
                  <div class="pd-lr-10 fz-14" style="color: #333;">|</div>
                  <div class="btn-delete" @click="handleDelete(scope.row.id)">删除</div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页 -->
        <el-pagination
          hide-on-single-page
          background
          style="align-self: flex-end;"
          layout="prev, pager, next, total, jumper"
          :total="queryInfo.total"
          :page-size="queryInfo.pageSize"
          @current-change="handlePageNoChange"
        />
      </div>
    </div>
    <SaveOrUpdate :visible.sync="dialogVisible" title="新建设备" @change="handleSearch" />
    <DeviceControl :visible.sync="deviceDialogVisible" />
    <el-dialog
      :visible.sync="isCreateVisible"
      title="批量导入"
      :width="handleScreenWidthToVw(574)+'px'"
      :close-on-click-modal="false"
      :before-close="closeFile"
    >
      <el-form>
        <p>说明：批量导入功能需下载模板填入设备信息</p>

        <el-form-item label="选择产品：" label-width="85px">
          <el-select v-model="productId" placeholder="请选择">
            <el-option
              v-for="product in options"
              :key="product.id"
              :label="product.name"
              :value="product.id"
            ></el-option>
          </el-select>
          <div class="download-button" @click="downloadTemplateExcel">下载模板</div>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <input type="file" name="filename" ref="filElem" @change="uploadHttpRequest" />
        <SubButton title="上传" @subClick="getFile" />
        <CancelButton @cancelClick="closeFile" />
      </span>
    </el-dialog>
    <!--    <player-dialog :url="playerUrl" :dialog-visible="isShowPlayer" @close="isShowPlayer = false" />-->
  </div>
</template>

<script>
// import AddButton from '@/components/add-button/index.vue'
import {
  apiFindDevicePageByParam,
  apiDelDeviceById,
  apiOpenPlayer,
  findPList,
  deviceTemplateExcel,
  checkoutDeviceExcel,
  importDevicesExcel,
} from './api'
// import PlayerDialog from './components/player-dialog'
import DeviceControl from './components/device-control'
import SelectProduct from '@/views/device/create-product/components/select-product'
import SelectDeviceState from './components/select-device-state'
import SelectOnlineState from './components/select-device-online-state'
// import SelectNetType from './components/select-net-type'
import SaveOrUpdate from './components/save-or-update-device'
import QueryContainer from '@/components/query-container'
import SubButton from '@/components/sub-button/index.vue'
import CancelButton from '@/components/cancel-button/index.vue'
import { handleScreenWidthToVw } from '@/utils/tools'
import dayjs from 'dayjs'
// import CustomButton from '@/components/custom-button'
import { CONST_URL } from '@/consts'

export default {
  name: 'DeployDevice',

  components: {
    QueryContainer,
    // AddButton,
    SelectProduct,
    SelectOnlineState,
    SelectDeviceState,
    // SelectNetType,
    SaveOrUpdate,
    DeviceControl,
    SubButton,
    CancelButton,
    // CustomButton,
    // PlayerDialog
  },

  data() {
    return {
      dialogVisible: false,
      isCreateVisible: false,
      queryInfo: {
        /**
         * @type {'EXTERNAL','INTERNAL'} deviceSourceEnum
         */
        deviceSourceEnum: 'INTERNAL',
        // 在线状态
        online: null,
        // 启用状态
        enableStateEnum: '',
        // 所属产品id
        productId: '',
        selectedProduct: {},
        // 入网类型
        netType: '',
        keyword: '',
        pageSize: 10,
        pageNo: 1,
        total: 0,
      },
      tableData: [],
      options: [],
      fileList: [],
      productId: null,
      loading: false,
      playerUrl: '',
      isShowPlayer: false,
      // 设备控制弹窗
      deviceDialogVisible: false,
    }
  },

  computed: {
    handleScreenWidthToVw() {
      return handleScreenWidthToVw
    },
  },

  created() {
    this.init()
  },
  methods: {
    async init() {
      this.options = await findPList()
      await this.findDevicePageByParam(this.queryInfo)
    },
    closeFile() {
      this.$refs.filElem.value = ''
      this.isCreateVisible = false
    },
    getFile() {
      this.$refs.filElem.dispatchEvent(new MouseEvent('click'))
    },
    async uploadHttpRequest() {
      const file = this.$refs.filElem.files[0]
      const extension = file.name.includes('xls')
      if (extension) {
        const formData = new FormData()
        formData.append('file', file)
        const res = this.flatArr(await checkoutDeviceExcel(formData))
        let resText = ''
        res.forEach((element, i) => {
          resText =
            resText +
            (i + 1) +
            '.' +
            element.colName +
            ' ：<br/> ' +
            element.errMsg +
            ' <br/><br/> '
        })
        if (res.length > 0) {
          this.$alert(resText, '上传错误', {
            confirmButtonText: '确定',
            dangerouslyUseHTMLString: true,
          })
        } else {
          await importDevicesExcel(formData)
          this.$message({
            message: '上传成功',
            type: 'success',
          })
        }
        this.$refs.filElem.value = ''
        this.isCreateVisible = false
      } else {
        this.$message({
          message: '上传模板只能是 xls、xlsx格式!',
          type: 'error',
        })
        this.$refs.filElem.value = ''
      }
    },
    flatArr(arr) {
      while (arr.some(t => Array.isArray(t))) {
        arr = [].concat.apply([], arr)
      }
      const res = arr.filter(item => {
        return item.errMsg
      })
      return res
    },
    // async uploadDeviceExcel() {
    //   //
    //   const formData = new FormData()
    //   const file = this.files[0]
    //   formData.append('file', file)
    //   const res = checkoutDeviceExcel(file)
    //   console.log(res)
    // },
    downloadTemplateExcel() {
      if (this.productId) {
        const fileName = '导入模板.xlsx'
        deviceTemplateExcel(this.productId).then(res => {
          // ;/=(.+\..*)/g.test(res.headers['content-disposition'].toString())
          // const fileName = decodeURI(RegExp.$1)

          const url = window.URL.createObjectURL(new Blob([res.data]), {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
          })

          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.download = `${dayjs().format('YYYY-MM-DD-HH-mm-ss')}-${fileName}`
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)
        })
      } else {
        this.$message({
          message: '请选择好产品后再下载模板！',
          type: 'error',
        })
      }
    },
    handlePageNoChange(pageNo) {
      this.queryInfo.pageNo = pageNo
      this.handleSearch()
    },
    handleReset() {
      this.$refs.queryForm.resetFields()
      this.handleSearch()
    },
    handleSearch() {
      this.findDevicePageByParam(this.queryInfo)
    },
    async handleOpenPlayer(item) {
      const data = {}
      data.deviceId = item.id
      data.ip = item.remark
      const res = await apiOpenPlayer({ ...data })
      this.playerUrl = res.outputMsg.result.result.play_url
      this.isShowPlayer = true
    },
    handleCreateGroup() {
      this.dialogVisible = true
    },
    handleEdit(device) {
      this.$router.push({ path: '/device/deploy-device-detail', query: { deviceId: device.id } })
    },
    handleNavToHeXin() {
      window.open(CONST_URL.HE_XIN_URL)
    },
    async findDevicePageByParam(queryInfo) {
      this.loading = true
      if (queryInfo.deviceSourceEnum && !queryInfo.deviceSourceEnum.length) {
        queryInfo.deviceSourceEnum = undefined
      }
      if (!queryInfo.enableStateEnum) {
        queryInfo.enableStateEnum = undefined
      }
      const { records, total } = await apiFindDevicePageByParam(queryInfo)
      this.tableData = records
      this.queryInfo.total = total
      this.loading = false
    },
    async handleDelete(deviceId) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          await apiDelDeviceById({ deviceId })
          this.$message.success('删除成功！')
          await this.findDevicePageByParam(this.queryInfo)
        } catch (msg) {
          this.$message.error(msg)
        }
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.vehicle-container {
  background-color: #f3f4f8;
  box-sizing: border-box;

  .content {
    padding: vw(20px);
    margin-top: vw(20px);
    background-color: #fff;
  }

  input[type='file'] {
    display: none;
  }

  .ENABLE {
    color: #67c23a;
  }

  .DISABLE {
    color: #f6a326;
  }

  .OFFLINE,
  .ONLINE {
    position: relative;

    &::after {
      display: inline-block;
      width: 10px;
      height: 10px;
      margin-left: 10px;
      border-radius: 50%;
      content: '';
    }
  }

  .ONLINE {
    &::after {
      background-color: #67c23a;
    }
  }

  .OFFLINE {
    &::after {
      background-color: #909399;
    }
  }

  .summery {
    height: 40px;
    border-radius: 4px;
    box-shadow: -1px 0 4px 0 rgba(29, 29, 29, 0.15);

    & > div {
      &:not(:last-child)::after {
        display: inline-block;
        width: 1px;
        height: 100%;
        background: linear-gradient(
          0deg,
          rgba(255, 255, 255, 0) 0%,
          rgba(153, 153, 153, 0.5) 26%,
          rgba(153, 153, 153, 0.99) 53%,
          rgba(153, 153, 153, 0.44) 79%,
          #fff 100%
        );
        content: '';
      }
    }

    .value {
      color: #0084ee;
    }
  }

  ::v-deep .el-form-item {
    margin-bottom: vh(20px);
  }

  .cell-style {
    color: #999;
  }
}

.query-container {
  display: flex;
  flex-direction: row;
}

.btn-edit {
  color: #0084ee;

  &:hover {
    cursor: pointer;
    opacity: 0.7;
  }
}

.btn-delete {
  color: #d12d1f;

  &:hover {
    cursor: pointer;
    opacity: 0.7;
  }
}

.download-button {
  color: #0084ee;

  &:hover {
    cursor: pointer;
    opacity: 0.7;
  }
}

::v-deep {
  .el-dialog__body {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    padding: vh(20px);
  }

  .el-form-item {
    margin-bottom: 0;
  }

  .el-table .caret-wrapper {
    height: vh(34px);
  }

  .el-table .sort-caret.ascending {
    top: vh(1px);
  }

  .el-table .sort-caret.descending {
    bottom: vh(4px);
    border-top-color: #c0c4cc;
  }
}
</style>
